/**
 * 文档作者: wj
 * 创建时间：2018年04月07日
 * 修改时间：2018年04月07日
 * 描述信息：swiper组件(图片轮播)
 */

import React, {Component} from 'react';

import './swiper.scss';

class Swiper extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startPageX: 0,
            move: window.innerWidth, // 下一张图片距离
            index: this.props.index - 1 || 0
        }
        this.divStyle = {
            transform: `translateX(-${this.state.index*this.state.move}px)`
        }
        this.interval = null;
        this.timeout = null;
        this.swiper = null;
    }
    render () {
        this.len = this.props.data.length - 1;  // 图片长度
        const el = this.props.data.map((value, index) => {
            return (
                <img key={value.image} onClick={this.onJump.bind({url: value.image, self: this})} alt="" src={value.image} />
            )
        });
        let round = '';
        let title;
        if (this.props.isShow) {
            title = [];
            round = this.props.data.map((value, index) => {
                title.push((index === this.state.index?<p key={value.id} className='title'>{value.title}</p>: ''))
                return (
                    <span key={index + 100} style={{color: this.state.index === index?'': 'white'}}>●</span>
                )
            });
        }
        return (
            <div className="swiper-component">
                <div className="swiper-main" style={this.divStyle} ref={(node) => {this.swiper = node}}>
                    {el}
                </div>
                <div className='bottom'>
                    {round}
                    {title}
                </div>
            </div>
        )
    }
    componentDidMount () {
        const el = this.props.isShow ? this.swiper : document.body
        el.addEventListener('touchstart', this.touchstart.bind(this));
        el.addEventListener('touchmove', this.touchmove.bind(this));
        el.addEventListener('touchend', this.touchend.bind(this));
        if (this.props.isShow) {
            this.interval = setInterval(() => {
                this.next();
            }, 3000);
        }
    }

    componentWillUnmount () {
        clearInterval(this.interval);
        clearTimeout(this.timeout);
        this.timeout = this.interval = null;
    }
    touchstart (event) {
        const touch = event.targetTouches[0];
        this.setState({startPageX: touch.pageX});
    }
    touchmove (event) {
        // 拖动平移
        if (event.changedTouches.length === 1) {
            const touch = event.changedTouches[0];
            const endX = touch.pageX;
            // 平移保留上次平移的值
            const result = endX - this.state.startPageX;
            if ((result < 0 && this.state.index < this.len) || (result > 0 && this.state.index !== 0)) {
                if(this.swiper) this.swiper.style.transform = `translateX(${result-this.state.move * this.state.index}px)`;
            }
        }
    }
    touchend (event) {
        const touch = event.changedTouches[0];
        const endX = touch.pageX;
        const result = endX - this.state.startPageX;
        if (Math.abs(result) > 60) {
            // 滑动大于60px切换图片  
            if (result < 0) { // 右滑
                this.next();
            } else { // 左滑
                this.prev();
            }
            clearInterval(this.interval);
            // 调用父组件方法
            this.props.imgMove && this.props.imgMove(this.state.index + 1);
        } else {
            // 滑动过小不切换图片
            if(this.swiper) this.swiper.style.transform = `translateX(-${this.state.move * (this.state.index)}px)`;
        }
    }
    // 下一张图片
    next() {
        this.setState({
            index: this.state.index + 1
        })
        if (this.state.index > this.len) {
            this.setState({
                index: 0
            });
        }
        for (let i = this.state.move * (this.state.index - 1); i < this.state.move * (this.state.index); i++) {
            this.timeout = setTimeout(() => {
                if (this.swiper) this.swiper.style.transform = `translateX(-${i+1}px)`;
            }, 100)
        }
    }
    // 上一张图片
    prev() {
        this.setState({
            index: this.state.index -1
        })
        if (this.state.index < 0) {
            this.setState({
                index: this.len
            });
        }
        if(this.swiper) this.swiper.style.transform = `translateX(-${this.state.move * (this.state.index)}px)`;
    }
    // 动画
    animate () {

    }
    /**
     * 点击图片跳转到文章页面
     */
    onJump() {
        
    }
}

export default Swiper
